<template>
  <view class="container" :style="appThemeStyle">
    <view class="tabs-wrap">
      <view class="tabs-scroll">
        <u-tabs
          bg-color="transparent"
          :list="channelTabs"
          name="channelName"
          color="#999"
          :current="channelIndex"
          @change="changeChannel"
          :is-scroll="true"
        ></u-tabs>
      </view>
      <view class="search" @click="handlePopup">
        <text>筛选</text>
        <text class="iconfont">&#xe6ae;</text>
      </view>
    </view>
    <view class="m-top16">
      <u-notice-bar
        bg-color="#FFFFFF"
        border-radius="16"
        type="none"
        mode="horizontal"
        :list="noticeBar"
      ></u-notice-bar>
    </view>
    <!-- 账单汇总 -->
    <view class="finance">
      <view class="header">
        <view class="title">账单汇总</view>
        <view class="tips">平台账户金额=线下核销金额-营销金额</view>
      </view>
      <view class="outer-wrap">
        <view class="head">
          <view class="text">正向单</view>
          <view class="desc">
            差额：
            <text class="red">{{ orderData.diffAmount }}</text>
          </view>
        </view>
        <view class="inter-wrap">
          <view class="item">
            <view class="name">应结金额</view>
            <view class="count">{{ orderData.channelDueAmount }}</view>
          </view>
          <view class="item">
            <view class="name">线下核销</view>
            <view class="count">{{ orderData.posAmount }}</view>
          </view>
          <view class="item">
            <view class="name">运营金额</view>
            <view class="count">{{ orderData.marketingAmount }}</view>
          </view>
        </view>
      </view>
      <view class="outer-wrap m-top16">
        <view class="head">
          <view class="text">逆向单</view>
          <view class="desc">
            差额：
            <text class="red">{{ refundData.diffAmount }}</text>
          </view>
        </view>
        <view class="inter-wrap">
          <view class="item">
            <view class="name">应结金额</view>
            <view class="count">{{ refundData.channelDueAmount }}</view>
          </view>
          <view class="item">
            <view class="name">线下核销</view>
            <view class="count">{{ refundData.posAmount }}</view>
          </view>
          <view class="item">
            <view class="name">运营金额</view>
            <view class="count">{{ refundData.marketingAmount }}</view>
          </view>
        </view>
      </view>
    </view>
    <!-- 账单明细 -->
    <view class="finance">
      <view class="header-title">销售渠道占比</view>
      <view class="select-list">
        <view
          :class="['select-item', { active: index === selectIndex }]"
          v-for="(item, index) in selectList"
          :key="index"
          @click="selectItem(index)"
        >
          {{ item.title }}
        </view>
      </view>
      <mescroll-body ref="mescrollRef" :sticky="true" @init="mescrollInit" :down="{ use: false }" :up="upOption" @up="upCallback">
        <view class="collapse">
          <view class="collapse-item" v-for="(item, index) in recordList" :key="index">
            <view class="normal-wrap" @click="onToggleShow(item)">
              <view class="collapse-head">
                <view class="left">
                  <view v-for="(v, j) in channelList" :key="j">
                    <view
                      v-if="v.channelId === item.thirdChannelId"
                      class="icon"
                      :style="{ backgroundColor: v.color }"
                    >{{ v.abbreviation || '无'}}</view>
                  </view>
                  <text>订单号 {{ item.channelOrderNo }}</text>
                </view>
                <view class="right">
                  <text class="text">已核销</text>
                  <text class="iconfont">{{ item.open ? '&#xe6ab;' : '&#xe6ac;' }}</text>
                </view>
              </view>
              <view class="order-wrap">
                <view class="order-cell">
                  <view>核销日期：{{ item.posTime || '--'}} </view>
                  <view class="right">核销金额：￥{{ item.posAmount }}</view>
                </view>
                <view class="order-cell">
                  <view>账单日期：{{ item.channelStatementDate || '--'}} </view>
                  <view class="right">应结金额：￥{{ item.channelDueAmount }}</view>
                </view>
              </view>
            </view>
            <view class="order-detail" v-show="item.open">
              <view class="order-item">
                <view> 佣金 </view>
                <view> ￥{{ item.commission }} </view>
              </view>
              <view class="order-item">
                <view> 商家单品补贴 </view>
                <view> ￥{{ item.goodsShopDiscAmount }} </view>
              </view>
              <view class="order-item">
                <view> 商家整单补贴 </view>
                <view> ￥{{ item.wholeShopDiscAmount }} </view>
              </view>
              <view class="order-item">
                <view> 商家运费补贴 </view>
                <view> ￥{{ item.deliveryShopDiscAmount }} </view>
              </view>
              <view class="order-item">
                <view> 平台单品补贴 </view>
                <view> ￥{{ item.goodsPlatformDiscAmount }} </view>
              </view>
              <view class="order-item">
                <view> 平台整单补贴 </view>
                <view> ￥{{ item.wholePlatformDiscAmount }} </view>
              </view>
              <view class="order-item">
                <view> 平台运费补贴 </view>
                <view> ￥{{ item.deliveryPlatformDiscAmount }} </view>
              </view>
              <view class="order-item">
                <view> 品牌单品补贴 </view>
                <view> ￥{{ item.goodsBrandDiscAmount }} </view>
              </view>
              <view class="order-item">
                <view> 品牌整单补贴 </view>
                <view> ￥{{ item.wholeBrandDiscAmount }} </view>
              </view>
              <view class="order-item">
                <view> 商家支付小费金额 </view>
                <view> ￥{{ item.payGratuityAmount }} </view>
              </view>
              <view class="order-item">
                <view> 取件服务费 </view>
                <view> ￥{{ item.distantRangeAmount }} </view>
              </view>
              <view class="order-price">
                <view> 营运金额 </view>
                <view> ￥{{ item.marketingDiscAmount }} </view>
              </view>
              <view class="order-item">
                <view> 差异金额 </view>
                <view> ￥{{ item.diffAmount }} </view>
              </view>
            </view>
          </view>
        </view>
      </mescroll-body>
    </view>

    <!-- 查询弹窗 -->
    <u-popup
      v-model="showPopup"
      mode="top"
      :closeable="false"
      border-radius="20"
      :mask-custom-style="{ background: 'rgba(0, 0, 0, 0.7)' }"
    >
      <!-- 标题 -->
      <view class="popup-wrap">
        <view class="change-list">
          <view
            :class="['change-item', { active: index === changeIndex }]"
            v-for="(item, index) in changeOptions"
            :key="index"
            @click="changeDropdown(index)"
          >{{ item.label }}</view>
        </view>
        <view class="date-wrap"  @click="onCalendar">
          <view class="date-item">
            <view :class="{ active: startTime }">{{ startTime || '开始日期' }}</view>
            <text class="iconfont calendar">&#xe6c6;</text>
          </view>
          <view class="date-item">
            <view :class="{ active: startTime }">{{ endTime || '结束日期' }}</view>
            <text class="iconfont calendar">&#xe6c6;</text>
          </view>
        </view>
        <view class="btn-wrapper">
          <view class="btn-item" @click="handleReset">重置</view>
          <view class="btn-item active" @click="handleSearch">筛选</view>
        </view>
      </view>
    </u-popup>

    <!-- 日历组件 -->
    <u-calendar
      max-date="2050-01-01"
      v-model="showTime"
      mode="range"
      @change="changeDate"
    ></u-calendar>
  </view>
</template>
<script>

import store from "@/store";
import * as FinanceApi from "@/api/finance"
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins'
import { getEmptyPaginateObj, getMoreListData } from '@/core/app'

export default {
  name: "index",
  mixins: [MescrollMixin],
  data() {
    return {
      channelTabs: [
        {
          thirdChannelId: '',
          channelName: '全部'
        }
      ],
      channelIndex: 0,
      changeOptions: [
        { label: '账单日期' },
        { label: '核销日期' },
      ],
      changeIndex: 0,
      startTime: this.$moment().format("YYYY-MM-DD"),
      endTime: this.$moment().format("YYYY-MM-DD"),
      showTime: false,
      noticeBar: ['核销日期筛选核对ERP回流，账单日期筛选核对平台账单'],
      selectList: [
        { title: '全部' },
        { title: '未核销' },
        { title: '差异金额' }
      ],
      selectIndex: 0,
      channelList: [],
      orderData: {},
      refundData: {},
      recordList: getEmptyPaginateObj(),
      // 上拉加载配置
      upOption: {
        // 首次自动执行
        auto: true,
        // 每页数据的数量; 默认10
        page: { size: 10 },
        // 数量要大于3条才显示无更多数据
        noMoreSize: 3,
        empty: {
          tip: '这里空空如也~'
        }
      },
      showPopup: false
    }
  },
  computed: {
    store() {
      return store.getters.store
    },
    channels() {
      return store.getters.channels
    },
    channelList() {
      return store.getters.allChannels
    }
  },
  onLoad() {
    const channel = this.channels.filter(item => item.thirdChannelId !== 17)
    this.channelTabs = [...this.channelTabs, ...channel]
  },
  onShow() {
    this.getBillOrderInfo()
  },
  methods: {
    handleReset() {
      this.startTime = ''
      this.endTime = ''
      this.changeIndex = 0
      this.showPopup = false
      this.onRefreshPage()
    },
    handleSearch() {
      this.showPopup = false
      this.onRefreshPage()
    },
    handlePopup() {
      this.showPopup = true
    },
    onCalendar() {
      this.showTime = true
    },
    changeDropdown(index) {
      this.changeIndex = index
    },
    changeDate(e) {
      this.startTime = this.$moment(e.startDate).format("YYYY-MM-DD")
      this.endTime = this.$moment(e.endDate).format("YYYY-MM-DD")
      this.showTime = false
    },
    changeChannel(index) {
      this.channelIndex = index
      this.onRefreshPage()
    },
    onToggleShow(item) {
      item.open = !item.open
    },
    selectItem(index) {
      this.selectIndex = index
      this.onRefreshPage()
    },
    onRefreshPage() {
      this.getBillOrderInfo()
      this.onRefreshList()
    },
    queryParams() {
      const startKey = this.changeIndex === 0 ? 'billStartTime' : 'posStartTime'
      const endKey = this.changeIndex === 0 ? 'billEndTime' : 'posEndTime'
      const params = {
        thirdChannelId: this.channelTabs[this.channelIndex].thirdChannelId,
        [startKey]: this.startTime,
        [endKey]: this.endTime,
      }
      if (this.store.id !== '0') params.organizationIds = this.store.id
      if (this.selectIndex === 1) params.posStatus = 1
      if (this.selectIndex === 2) params.hasDiff = 1
      return params
    },
    getBillOrderInfo() {
      FinanceApi.getBillOrderInfo(this.queryParams(), { load: false }).then(res => {
        const { orderData, refundData } = res.data
        this.orderData = orderData
        this.refundData = refundData
      }).catch(() => {})
    },
    // 刷新列表
    onRefreshList() {
      this.recordList = getEmptyPaginateObj()
      setTimeout(() => {
        this.mescroll.resetUpScroll()
      }, 120)
    },
    /**
     * 上拉加载的回调 (页面初始化时也会执行一次)
     * 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
     * @param {Object} page
     */
    upCallback(page) {
      this.getBillOrdersPage(page.num)
        .then(res => {
          const curPageLen = res.length
          this.mescroll.endBySize(curPageLen)
        })
        .catch(() => this.mescroll.endErr())
    },
    /**
     * 获取销售占比列表
     * @param {Number} current 页码
     */
    getBillOrdersPage(current = 1) {
      return new Promise((resolve, reject) => {
        FinanceApi.getBillOrdersPage({ ...this.queryParams(), current }, { load: false })
          .then(result => {
            // 合并新数据
            const newList = this.initList(result.data)
            this.recordList = getMoreListData(newList, this.recordList, current)
            resolve(newList)
          })
          .catch(reject)
      })
    },
    // 初始化列表数据
    initList(newList) {
      newList.forEach(item => {
        item.isOpen = false
      })
      return newList
    },
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 24rpx;

  .tabs-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .tabs-scroll {
      width: 80%;
    }

    .search {
      width: 128rpx;
      height: 56rpx;
      line-height: 56rpx;
      text-align: center;
      background: #fff;
      font-size: 28rpx;
      border-radius: 8rpx;

      .iconfont {
        margin-left: 10rpx;
        color: #999;
      }
    }
  }

  .finance {
    background: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-top: 16rpx;

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 32rpx;
    }

    .title {
      font-size: 32rpx;
      font-weight: bold;
    }

    .tips {
      font-size: 24rpx;
      color: #666666;
    }

    .outer-wrap {
      background: #F5F6F9;
      padding: 24rpx;
      border-radius: 16rpx;

      .head {
        margin-bottom: 24rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 28rpx;

        .text {
          font-weight: bold;
        }

        .desc {
          color: $vice-text;

          .red {
            color: #F53F3F;
          }
        }
      }

      .inter-wrap {
        margin-top: 24rpx;
        display: flex;

        .item {
          flex: 1;
          text-align: center;

          .name {
            color: $vice-text;
            font-size: 26rpx;
          }

          .count {
            margin-top: 24rpx;
            font-size: 30rpx;
            font-weight: bold;
          }
        }
      }
    }

    .select-list {
      margin-top: 32rpx;
      display: flex;

      .select-item {
        margin-right: 16rpx;
        border-radius: 8rpx;
        border: 1rpx solid var(--eeeeee, #EEE);
        background: #FFF;
        font-size: 24rpx;
        color: #666666;
        padding: 10rpx 24rpx;

        &.active {
          background: #f8f8f8;
          color: #333333;
          font-weight: bold;
        }
      }
    }

    .collapse {
      margin-top: 30rpx;

      .collapse-item {
        padding: 26rpx 0;
        border-bottom: 1rpx dashed #999;

        &:last-child {
          border: none;
        }

        .collapse-head {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 24rpx;

          .left {
            display: flex;
            align-items: center;

            .icon {
              margin-right: 10rpx;
              padding: 5rpx 6rpx;
              background: #fdd001;
              color: #ffffff;
              border-radius: 2px;
              font-size: 18rpx;
            }

            .order-num {
              font-size: 28rpx;
              font-weight: bold;
            }
          }

          .right {
            color: $main-bg;
            font-size: 28rpx;

            .text {
              margin-right: 20rpx;
            }

            .iconfont {
              color: #999;
            }
          }
        }

        .order-wrap {

          .order-cell {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 24rpx;
            color: #666666;
            margin: 16rpx 0;

            .right {
              width: 260rpx;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
        }

        .order-detail {
          padding: 20rpx;
          background: #f8f8f8;

          .order-item {
            margin: 10rpx 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 24rpx;
          }

          .order-price {
            font-size: 24rpx;
            color: #666666;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            border-bottom: 1px solid#EEEEEE;
            padding-bottom: 20rpx;

            &:last-child {
              color: #333333;
              margin-left: 20rpx;
            }
          }
        }
      }
    }
  }

  .popup-wrap {
    padding: 32rpx;

    .page-title {
      font-size: 28rpx;
      color: #666666;
    }

    .change-list {
      display: flex;

      .change-item {
        margin-right: 16rpx;
        border-radius: 16rpx;
        background: #F8F8F8;
        font-size: 24rpx;
        color: #666666;
        padding: 14rpx 30rpx;

        &.active {
          background: #2D71FD;
          color: #ffffff;
        }
      }
    }

    .date-wrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 40rpx 0;

      .date-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12rpx 20rpx;
        background: #F8F8F8;
        font-size: 24rpx;
        color: #cccccc;
        border-radius: 16rpx;
        width: 330rpx;

        .active {
          color: #333;
        }

        .calendar {
          margin-left: 30rpx;
          color: #999;
          font-size: 30rpx;
        }
      }
    }

    .btn-wrapper {
      display: flex;
      justify-content: space-between;

      .btn-item {
        width: 330rpx;
        height: 96rpx;
        line-height: 96rpx;
        text-align: center;
        background: #fff;
        font-size: 34rpx;
        border-radius: 16rpx;
        border: 2rpx solid var(--eeeeee, #EEE);

        &.active {
          background: $main-bg;
          color: #fff;
        }
      }
    }
  }

  /* 隐藏滚动条 */
  ::-webkit-scrollbar {
    width: 0;
    height: 0;
    color: transparent;
  }
}
</style>
